package com.cszy.yydqbfq.base

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.cszy.yydqbfq.dialog.PermissoTipDialog
import com.cszy.yydqbfq.dialog.UserRefusedPermissonDialog
import com.cszy.yydqbfq.ext.toast
import com.cszy.yydqbfq.utils.SpUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions

import java.lang.reflect.ParameterizedType

abstract class BaseVMFragment<VM : BaseViewModel, VB : ViewBinding> : BaseFragment<VB, Any?>() {

    lateinit var mViewModel: VM
    private var pernissonTopdialog: PermissoTipDialog? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        createViewModel()
        lifecycle.addObserver(mViewModel)
        registerEvent()
        super.onViewCreated(view, savedInstanceState)
    }


     fun request_Permission(
        context: Activity,
        req_permisson: String,
        permisson_name: String,
        content: String
    ) {
        // 检查是否已标记为"不再询问"
        if (!SpUtils.getInstance().getBoolean(permisson_name)) { // 没有获取该权限或者没有永久拒绝
            showPermissonTipsDialog(context, content)
        }
        XXPermissions.with(context)
            // 申请单个权限
            .permission(req_permisson)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (pernissonTopdialog != null) {
                        pernissonTopdialog!!.dismiss()
                    }
                    if (!allGranted) {

                        return
                    }
                    SpUtils.getInstance().putBoolean(permisson_name, true)
                    toast("获取 $permisson_name 权限成功")
                    loadAudioList()
                }



                override fun onDenied(
                    permissions: MutableList<String>,
                    doNotAskAgain: Boolean
                ) {
                    if (doNotAskAgain) {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }
                        showDoNotAskAgainDialog(
                            context,
                            req_permisson,
                            permisson_name
                        )
                    } else {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }

                    }
                }
            })
    }

    fun showMediaPermissionDialog() {
        if (XXPermissions.isGranted(
                requireContext(),
                android.Manifest.permission.READ_MEDIA_AUDIO
            )
        ) {
            loadAudioList()
        } else {
            request_Permission(
                requireActivity(),
                android.Manifest.permission.READ_MEDIA_AUDIO,
                "音频权限",
                "应用需要访问取您的存储权限，获取整个设备的音频文件资源用于播放器播放设备音乐"
            )
        }
    }


    open fun loadAudioList(){

    }


    /**
     * 用户单次拒绝
     */
    fun showPermissonTipsDialog(context: Context, content: String) {
        pernissonTopdialog = PermissoTipDialog(context)
        pernissonTopdialog!!.setPermissionMessage(content)
        pernissonTopdialog!!.show()
        pernissonTopdialog!!.setCancelable(false)
    }

    /**
     * 用户多次拒绝
     */
    fun showDoNotAskAgainDialog(context: Context, permission: String, permissionName: String) {
        var dialog = UserRefusedPermissonDialog(context,permission)
        dialog.setPermissionMessage("您未授予 $permissionName 权限，请去设置中开启")
        dialog.setCancelable(false)
        dialog.show()
    }


    /**
     * 注册事件
     */
    private fun registerEvent() {
        mViewModel.ui.showDialog.observe(viewLifecycleOwner) {
            showLoading(it)
        }
        mViewModel.ui.dismissDialog.observe(viewLifecycleOwner) {
            dismissLoading()
        }
        mViewModel.ui.toast.observe(viewLifecycleOwner) {
            toast(it)
        }
        mViewModel.ui.msgEvent.observe(viewLifecycleOwner) {
            handleEvent(it)
        }
    }

    /**
     * 创建 ViewModel
     * 共享 ViewModel的时候,重写Fragment的getViewModelStore()方法，
     * 返回 activity的ViewModelStore或者父Fragment的ViewModelStore
     */
    @Suppress("UNCHECKED_CAST")
    private fun createViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val tp = type.actualTypeArguments[0]
            val tClass = tp as? Class<VM> ?: BaseViewModel::class.java
            mViewModel = ViewModelProvider(this)[tClass] as VM
        }
    }

}